package com.sx.mvvmlibs.event

import androidx.annotation.MainThread
import androidx.lifecycle.LifecycleOwner
import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.Observer
import com.sx.mvvmlibs.utils.Logs
import java.util.concurrent.atomic.AtomicBoolean

/**
 * @Author YY
 * @Date 2021/4/4
 * @Description 解决LiveData或者MutableLiveData多次回调的问题
 */
class SingleLiveEvent<T> : MutableLiveData<T?>() {

    private val mPending = AtomicBoolean(false)

    @MainThread
    override fun observe(owner: LifecycleOwner, observer: Observer<in T?>) {
        if (hasActiveObservers()) {
            Logs.w("已注册多个观察员，但只有一个观察员会收到更改通知")
        }

        // 观察内部的可变LiveData
        super.observe(owner, Observer { t: T? ->
            if (mPending.compareAndSet(true, false)) {
                observer.onChanged(t)
            }
        })
    }

    @MainThread
    override fun setValue(t: T?) {
        mPending.set(true)
        super.setValue(t)
    }

    @MainThread
    fun call() {
        value = null
    }
}